package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.JSoupUtils;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;

public class FccsNewsAnalyse implements AnalyseNews {

	
	public boolean isDetailPage(String url) {
		boolean bRet=false;

		String[] regex={
							"http://.*.fccs.com/news/[0-9]{6}/[0-9]+.shtml"
							};
		for (int i=0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				bRet=true;
				break;
			}
		}
		return bRet;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		String url=urlMeta.getUrl();
		String html=urlMeta.getHtml();
		String title="";
		String content="";
		Long date=0l;
		int commentNum=0;
		int clickNum=0;
		NewsMeta meta=new NewsMeta();
		meta.setUrl(url);
		meta.setType(0);
		if (html == null) {
		}
		Document doc=Jsoup.parse(html);
		if(html.startsWith("<script language=\"javascript\">")){
			UrlMeta responseToURL=CrawlHTML.responseToURL(StringUtils.substringBetween(html, "window.location.href=\"", "\";"));
			if(responseToURL!=null){
				html= responseToURL.getHtml();
				doc=Jsoup.parse(html);
				title=doc.select("#subject_tpc").text();
				content=HtmlCleaner.getContentHtml(url,doc.select("#read_tpc"));
				date=DateUtils.matchDate(doc.select("div.tipTop>span").attr(title));
				if(date==null){
					date=DateUtils.matchDate(doc.select("div.tipTop>span").text());
				}
			}
		}else{

			urlMeta=null;
			/*
			 * 解析新闻标题
			 */
			title=doc.select("p.col2Title_1.plr22.tc.pb18").text();
			/*
			 * 解析时间
			 */
			date=DateUtils.matchDate(doc.select("p.tc.plr22.pb18").text());
			/*
			 * 解析内容
			 */
			content=HtmlCleaner.getContentHtml(url,doc.select("div.col2_text.mlr22.resizeimg.pt.mt15"));
		}

		if (StringUtils.isBlank(title)) {
			title=doc.select("title").text();
			title=StringUtils.substringBefore(title, "_");
		}

		String author=JSoupUtils.matchAuthor(doc, "来源：");
		meta.setAuthor(author);
		meta.setTitle(title);
		meta.setContent(content);
		meta.setDate(date);
		meta.setClickNum(clickNum);
		meta.setCommentNum(commentNum);

		return meta;
	}


	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	public static void main(String[] args) {
		String url="http://sh.fccs.com/news/201401/4151467.shtml";
		UrlMeta urlMeta=CrawlHTML.responseToURL(url);
		FccsNewsAnalyse a=new FccsNewsAnalyse();
		boolean detailPage=a.isDetailPage(url);
		if (detailPage) {
			NewsMeta parserHtml=a.parserHtml(urlMeta);
			System.out.println(parserHtml);
		} else {
			System.out.println("不符合正则");
		}

	}
	
	public boolean isNeedUpdate(){
		return false;
	}
}
